package com.axonactive.yolo.controller;
import java.util.Arrays;
import java.util.Date;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.context.Context;

import com.axonactive.yolo.dto.Email;
import com.axonactive.yolo.service.interfaces.EmailService;

@Controller
public class EmailController {

	private static final Logger LOGGER = Logger.getLogger(EmailController.class);

	private static final String EMAIL = "email";
	private static final String MESSAGE = "message";

	@Autowired
	EmailService emailService;

	@RequestMapping(value = { "/email" }, method = RequestMethod.GET)
	public ModelAndView search() {
		return new ModelAndView(EMAIL);
	}

	@RequestMapping(value = { "/email" }, method = RequestMethod.POST)
	public ModelAndView sendEmail(
			@RequestParam(value = "recipientName", required = true) String recipientName,
			@RequestParam(value = "recipientEmail", required = true) String recipientEmail) {
		try {
			Email email = new Email();
			email.setSubject("Test");
			email.setTo(recipientEmail);
			email.setTemplate("email-template");

			Context ctx = new Context();
			ctx.setVariable("name", recipientName);
			ctx.setVariable("subscriptionDate", new Date());
			ctx.setVariable("airlines",
					Arrays.asList("Viet Nam Airline", "Jetstar", "Viet Jet"));

			email.setBody(ctx);
			emailService.sendEmail_(email);
			return new ModelAndView(EMAIL, MESSAGE,
					"Success! The e-mail has been sent, please check your inbox.");
		} catch (Exception e) {
			LOGGER.info("Send Email Error", e);
			return new ModelAndView(EMAIL, MESSAGE, "An ERROR happened !");
		}
	}

}
